package cn.edu.scau.intercepter;


import cn.edu.scau.bean.ResultBean;
import cn.edu.scau.config.Audience;
import cn.edu.scau.util.JWTTokenUtil;
import com.alibaba.fastjson.JSON;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截器：访问特定的页面，必须保证用户的登录
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private Audience audience;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //从session中获取management对象信息
//        Management management = (Management) request.getSession().getAttribute("management");
//        //判断session中保存的management对象信息,重定向至登陆页面
//        if(management == null || StringUtils.isBlank(management.getName())){
//            if(!response.isCommitted()){
//                System.out.println("拦截对象");
//                response.sendRedirect("/login");
//            }
//
//        }
//        //正常流程请求允许通过
//        System.out.println("正常通过");
//        return true;
//        使用JWT
        //ajax提交两次,第一次提交，提交方式OPTIONS，必须放行
        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            return true;
        }
//        获取请求头token的内容
        final String token = request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY);
        //验证token的合法性，通过则可以继续访问指定的连接请求
        if(null!=token&&!JWTTokenUtil.isExpiration(token,audience.getBase64Secret())){
            return true;
        }
        //以下代码,是不通过的情况下，给请求者对应的信息提示
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        ResultBean r = new ResultBean(5009,false,"登陆已过期","");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(r));
        return false;
    }
}
